﻿using System;
using System.Web.UI.WebControls;
using MaLu.Common;
using MaLu.Data;
using System.Data;
using System.Text;
using Wicresoft.Framework.Organization;
using MaLu.Framework.Common;

namespace MaluJg.web.Villages
{
    public partial class VBusiEdit : VBusiPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = "村务添加";
            ScriptManager1.RegisterAsyncPostBackControl(lbtnSave);
            ScriptManager1.RegisterAsyncPostBackControl(btnAdd);
            ScriptManager1.RegisterAsyncPostBackControl(btnAdd2);
            if (!IsPostBack)
            {
                Department mainD = OrganizationHelper.GetDepartmentInfo(CurrentUser.MainDepartmentID);
                string[] ids = mainD.IDPath.Split('/');
                if (ids.Length >= 4)
                    DepartmentID = new Guid(ids[3]);
                else
                    DepartmentID = new Guid(ids[ids.Length - 1]);

                Binddata();
                BindDataYuSuan();
                BindDataJieSuan();
            }

        }
        private Guid RecordID
        {
            get
            {
                Guid gd = Guid.NewGuid();
                if (Request["ID"] != null)
                    gd = new Guid(Request["ID"]);
                else
                {
                    if (ViewState["ID"] != null)
                        gd = (Guid)ViewState["ID"];


                }
                if (ViewState["ID"] == null)
                    ViewState["ID"] = gd;
                return gd;
            }
            set
            {
                ViewState["ID"] = value;
            }

        }
        protected void lbtnSave_Click(object sender, EventArgs e)
        {
            Department dept = OrganizationHelper.GetDepartmentInfo(DepartmentID);
            if (dept != null)
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendFormat("declare @id uniqueidentifier; select @id=id from [VillageBusiness] where id='{0}';", RecordID);

                sql.AppendLine("if (@@rowcount=0) begin ");
                sql.AppendFormat(@"INSERT INTO [VillageBusiness]
           ([ID],[VillageName],[PreContent],[OverView]
           ,[RenQiTarget],[DivideWork],[Component]
           ,[YearTarget],[Reward],[Housing],[PropertyRent]
           ,[Projects],[Balances],[Financing]
           ,[EarchCompensationUse],[Outing],[Helps]
           ,[PolicyExecution],[ConstructionProject]
           ,[Others],[DepartmentID],[DepartmentDspName]
           ,[Creator],[CreateTime])   VALUES
           ('{0}',{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},
{15},{16},{17},{18},{19},'{20}','{21}','{22}',getdate())", RecordID, Util.ReturnSqlValue(tbVillage.Text)
              , Util.ReturnSqlValue(tbPreContent.Text), Util.ReturnSqlValue(tbOverView.Text), Util.ReturnSqlValue(tbRenQiTarget.Text), 
              Util.ReturnSqlValue(tbDivideWork.Text), Util.ReturnSqlValue(tbComponent.Text), Util.ReturnSqlValue(tbYearTarget.Text), 
              Util.ReturnSqlValue(tbReward.Text), Util.ReturnSqlValue(tbHousing.Text), Util.ReturnSqlValue(tbPropertyRent.Text),
              Util.ReturnSqlValue(tbProjects.Text), Util.ReturnSqlValue(tbBalances.Text), Util.ReturnSqlValue(tbFinancing.Text)
              , Util.ReturnSqlValue(tbEarchCompensationUse.Text), Util.ReturnSqlValue(tbOuting.Text), Util.ReturnSqlValue(tbHelps.Text), 
              Util.ReturnSqlValue(tbPolicyExecution.Text), Util.ReturnSqlValue(tbConstructionProject.Text), Util.ReturnSqlValue(tbOthers.Text),
              DepartmentID, dept.DisplayName,CurrentUser.Name);

                sql.AppendLine("end else ");
                sql.AppendLine("begin ");
                sql.AppendFormat("print 1;");
                sql.AppendFormat(@"UPDATE [VillageBusiness]
   SET [VillageName] = {0}  ,[PreContent] = {1}  ,[OverView] ={2}  ,[RenQiTarget] ={3}
      ,[DivideWork] = {4} ,[Component] = {5},[YearTarget] ={6}  ,[Reward] ={7}
      ,[Housing] = {8} ,[PropertyRent] = {9} ,[Projects] = {10}
      ,[Balances] = {11} ,[Financing] ={12} ,[EarchCompensationUse] = {13}
      ,[Outing] = {14} ,[Helps] = {15}  ,[PolicyExecution] ={16}
      ,[ConstructionProject] = {17} ,[Others] ={18}  ,[Creator] = '{19}'
      ,[ModifyTime] =getdate()
 WHERE ID='{20}'", Util.ReturnSqlValue(tbVillage.Text)
              , Util.ReturnSqlValue(tbPreContent.Text), Util.ReturnSqlValue(tbOverView.Text), Util.ReturnSqlValue(tbRenQiTarget.Text),
              Util.ReturnSqlValue(tbDivideWork.Text), Util.ReturnSqlValue(tbComponent.Text), Util.ReturnSqlValue(tbYearTarget.Text),
              Util.ReturnSqlValue(tbReward.Text), Util.ReturnSqlValue(tbHousing.Text), Util.ReturnSqlValue(tbPropertyRent.Text),
              Util.ReturnSqlValue(tbProjects.Text), Util.ReturnSqlValue(tbBalances.Text), Util.ReturnSqlValue(tbFinancing.Text)
              , Util.ReturnSqlValue(tbEarchCompensationUse.Text), Util.ReturnSqlValue(tbOuting.Text), Util.ReturnSqlValue(tbHelps.Text),
              Util.ReturnSqlValue(tbPolicyExecution.Text), Util.ReturnSqlValue(tbConstructionProject.Text), Util.ReturnSqlValue(tbOthers.Text), CurrentUser.Name, RecordID);
                sql.AppendLine("end   ");
                SqlHelper.Instance.ExecuteNonQuery(Provider, sql.ToString());
            }

            System.Web.UI.ScriptManager.RegisterStartupScript(UpdatePanel3, this.GetType(), "save", "alert('成功保存!')", true);
            UpdatePanel3.Update();
        }

        private void Binddata()
        {
            DataTable dt = SqlHelper.Instance.ExecuteDataTable(Provider, "select * from VillageBusiness  where id ='" + RecordID + "'");
            if (dt.Rows.Count > 0)
            {
                this.Title = "村务编辑";
                lbtnSave.Text = "<span ><img src=\"../Images/Icon/Action/save.gif\" alt=\"保存\" /></span><span>保存</span>";
                DataRow dr = dt.Rows[0];

                tbVillage.Text = dr["VillageName"].ToString().Replace("''", "'");
                tbPreContent.Text = dr["PreContent"].ToString().Replace("''", "'");
                tbOverView.Text = dr["OverView"].ToString().Replace("''", "'");
                tbRenQiTarget.Text = dr["RenQiTarget"].ToString().Replace("''", "'");
                tbDivideWork.Text = dr["DivideWork"].ToString().Replace("''", "'");
                tbComponent.Text = dr["Component"].ToString().Replace("''", "'");
                tbYearTarget.Text = dr["YearTarget"].ToString().Replace("''", "'");
                tbReward.Text = dr["Reward"].ToString().Replace("''", "'");
                tbHousing.Text = dr["Housing"].ToString().Replace("''", "'");
                tbPropertyRent.Text = dr["PropertyRent"].ToString().Replace("''", "'");
                tbProjects.Text = dr["Projects"].ToString().Replace("''", "'");
                tbBalances.Text = dr["Balances"].ToString().Replace("''", "'");
                tbFinancing.Text = dr["Financing"].ToString().Replace("''", "'");
                tbEarchCompensationUse.Text = dr["EarchCompensationUse"].ToString().Replace("''", "'");
                tbOuting.Text = dr["Outing"].ToString().Replace("''", "'");
                tbHelps.Text = dr["Helps"].ToString().Replace("''", "'");
                tbPolicyExecution.Text = dr["PolicyExecution"].ToString().Replace("''", "'");
                tbConstructionProject.Text = dr["ConstructionProject"].ToString().Replace("''", "'");
                tbOthers.Text = dr["Others"].ToString().Replace("''", "'");
            }
        }
        #region repeater1


        protected void rptItemList_ItemDataBound(object source, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemIndex >= 0)
            {
                DataRowView drv = e.Item.DataItem as DataRowView;
                LinkButton lbtnDelete = e.Item.FindControl("lbtnDelete") as LinkButton;
                lbtnDelete.CommandArgument = drv["ID"].ToString();
                LinkButton lbtnEdit = e.Item.FindControl("lbtnEdit") as LinkButton;
                lbtnEdit.CommandArgument = drv["ID"].ToString();

            }
        }
        protected void rptItemList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Delete":


                    SqlHelper.Instance.ExecuteNonQuery(Provider, "delete from VillageFinance where id='" + e.CommandArgument + "'");
                    BindDataYuSuan();

                    break;
                case "Edit":
                    DataTable dt = SqlHelper.Instance.ExecuteDataTable(Provider, "select * from VillageFinance where id='" + e.CommandArgument + "'");
                    if (dt.Rows.Count > 0)
                    {
                        DataRow dr = dt.Rows[0];
                        tbYear1.Text = dr["Year"].ToString();
                        tbYuSuan.Text = dr["Name"].ToString();
                        tbYsJe.Text = dr["Amount"].ToString();
                        tbID1.Text = dr["ID"].ToString();

                        btnAdd.Text = "<span ><img src=\"../Images/Icon/Action/save.gif\" alt=\"保存\" /></span><span>保存</span>";
                        UpdatePanel1.Update();
                    }
                    break;
            }
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (tbID1.Text == string.Empty)
            {

                string sql = string.Format(@"INSERT INTO [VillageFinance]
           ([ID]
           ,[VillageRecordID]
           ,[Year]
           ,[Name]
           ,[Amount]
           ,[FinancialType],CreateTime)
     VALUES
           (newid(),'{0}',{1},{2},'{3}',N'预算',getdate())", RecordID, tbYear1.Text, Util.ReturnSqlValue(tbYuSuan.Text), tbYsJe.Text);

                SqlHelper.Instance.ExecuteNonQuery(Provider, sql);
            }
            else
            {
                string sql = string.Format(@"UPDATE [VillageFinance]
   SET [Year] = {0} ,[Name] = {1},[Amount] =  '{2}'  WHERE ID='{3}'", tbYear1.Text, Util.ReturnSqlValue(tbYuSuan.Text), tbYsJe.Text, tbID1.Text);

                SqlHelper.Instance.ExecuteNonQuery(Provider, sql);
                btnAdd.Text = "<span ><img src=\"../Images/add.png\" alt=\"单条添加\" /></span><span>单条添加</span>";


            }
            BindDataYuSuan();


            tbYsJe.Text = string.Empty;
            tbYear1.Text = string.Empty;
            tbYuSuan.Text = string.Empty;
            tbID1.Text = string.Empty;
            UpdatePanel1.Update();
        }

        private void BindDataYuSuan()
        {
            DataTable dt = SqlHelper.Instance.ExecuteDataTable(Provider, "select ID, [Year] ,[Name]  ,[Amount]  from  [VillageFinance] where [FinancialType]='预算' and VillageRecordID='"+RecordID+"' order by createtime desc ");
            rptItemList.DataSource = dt;
            rptItemList.DataBind();

        }
        #endregion

        #region repeater2


        private void BindDataJieSuan()
        {
            DataTable dt = SqlHelper.Instance.ExecuteDataTable(Provider, "select ID, [Year] ,[Name]  ,[Amount]  from  [VillageFinance] where [FinancialType]='结算' and VillageRecordID='" + RecordID + "' order by createtime desc ");
            rptItemList2.DataSource = dt;
            rptItemList2.DataBind();

        }
        protected void rptItemList2_ItemDataBound(object source, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemIndex >= 0)
            {
                DataRowView drv = e.Item.DataItem as DataRowView;
                LinkButton lbtnDelete = e.Item.FindControl("lbtnDelete") as LinkButton;
                lbtnDelete.CommandArgument = drv["ID"].ToString();
                LinkButton lbtnEdit = e.Item.FindControl("lbtnEdit") as LinkButton;
                lbtnEdit.CommandArgument = drv["ID"].ToString();

            }
        }
        protected void rptItemList2_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Delete":


                    SqlHelper.Instance.ExecuteNonQuery(Provider, "delete from VillageFinance where id='" + e.CommandArgument + "'");
                    BindDataJieSuan();

                    break;
                case "Edit":
                    DataTable dt = SqlHelper.Instance.ExecuteDataTable(Provider, "select * from VillageFinance where id='" + e.CommandArgument + "'");
                    if (dt.Rows.Count > 0)
                    {
                        DataRow dr = dt.Rows[0];
                        tbYear2.Text = dr["Year"].ToString();
                        tbYuSuan2.Text = dr["Name"].ToString();
                        tbYsJe2.Text = dr["Amount"].ToString();
                        tbID2.Text = dr["ID"].ToString();

                        btnAdd2.Text = "<span ><img src=\"../Images/Icon/Action/save.gif\" alt=\"保存\" /></span><span>保存</span>";
                        UpdatePanel2.Update();
                    }
                    break;
            }
        }
        protected void btnAdd2_Click(object sender, EventArgs e)
        {
            if (tbID1.Text == string.Empty)
            {

                string sql = string.Format(@"INSERT INTO [VillageFinance]
           ([ID]
           ,[VillageRecordID]
           ,[Year]
           ,[Name]
           ,[Amount]
           ,[FinancialType],CreateTime)
     VALUES
           (newid(),'{0}',{1},{2},{3},N'结算',getdate())", RecordID, tbYear2.Text,Util.ReturnSqlValue( tbYuSuan2.Text),Util.ReturnSqlValue( tbYsJe2.Text));

                SqlHelper.Instance.ExecuteNonQuery(Provider, sql);
            }
            else
            {
                string sql = string.Format(@"UPDATE [VillageFinance]
   SET [Year] = {0} ,[Name] = {1},[Amount] =  {2}  WHERE ID='{3}'", tbYear2.Text, Util.ReturnSqlValue(tbYuSuan2.Text), Util.ReturnSqlValue(tbYsJe2.Text), tbID2.Text);

                SqlHelper.Instance.ExecuteNonQuery(Provider, sql);
                btnAdd2.Text = "<span ><img src=\"../Images/add.png\" alt=\"单条添加\" /></span><span>单条添加</span>";


            }
            BindDataJieSuan();


            tbYsJe2.Text = string.Empty;
            tbYear2.Text = string.Empty;
            tbYuSuan2.Text = string.Empty;
            tbID2.Text = string.Empty;
            UpdatePanel2.Update();
        }
        #endregion
    }
}
